package com.ruge.test.springMVC.jsp基础学习;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 爱丽丝、如歌  创建于 2018/6/25 15:51
 * 说明:  TODO
 */
@Controller
@RequestMapping(value = "springmvc")
public class jsp基础学习 {
    @RequestMapping(value = "jspInit.do")
    public String init() {
        return "jsp基础学习/demo01_page";
    }

    @RequestMapping(value = "testPost", method = RequestMethod.POST)
    public void testPost(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println(userName + " " + passWord + " " + Arrays.asList(hobbies));

    }

    @RequestMapping(value = "testGet", method = RequestMethod.GET)
    public void testGet(HttpServletRequest request, HttpServletResponse response) {
    }

    @RequestMapping(value = "gotoLogin.do")
    public String gotoLogin() {
        return "jsp基础学习/login";
    }

    @RequestMapping(value = "login.do")
    public String login(String userName, String passWord, String remberMe, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        if ("on".equals(remberMe)) {
            /**
             * 把用户名和密码保存在cookie中
             */
            Cookie cookieUserName = new Cookie("userName", userName);//创建新cookie
            Cookie cookiePassWord = new Cookie("passWord", passWord);//创建新cookie
            /**
             * cookie一分钟
             */
            cookieUserName.setMaxAge(5 * 60);// 设置存在时间为5分钟
            cookiePassWord.setMaxAge(5 * 60);// 设置存在时间为5分钟

            response.addCookie(cookieUserName);
            response.addCookie(cookiePassWord);
        } else {
            Cookie[] cookies = request.getCookies();//根据请求数据，找到cookie数组

            //如果没有cookie数组
            if (null == cookies) {
                System.out.println("没有cookie");
            } else {
                for (Cookie c : cookies
                        ) {
                    if ("userName".equals(c.getName()) || "passWord".equals(c.getName())) {
                        c.setMaxAge(0); // 设置cookie失效
                        c.setValue(null);
                        response.addCookie(c); // 重新保存
                    }
                }
            }
        }
        return "jsp基础学习/loginSuccess";
    }
}
